#include <functional>
#include "socket.hpp"

using func_t = std::function<string(string& packageBuffef)>;

class tcpServer{
public:
    tcpServer(uint16_t port, func_t callBack)
        :_port(port)
        ,_callBack(callBack)
    {}

    bool init(){
        listenSocket.creSocket();
        listenSocket.Bind(_port);
        listenSocket.Listen();
        return true;
    }

    void start(){
        while(true){
            string clientIP;
            uint16_t clientPort;
            int fd = listenSocket.Accept(&clientIP, &clientPort);
            if(fd < 0)
                continue;
            ls(Info, "listenSocket.Accept success");

            // 执行任务
            if(fork() == 0){
                ls(Info, "fork success");
                listenSocket.Close();
                string packageBuffer;
                while(true){
                    char buffer[128];
                    int n = read(fd, buffer, sizeof(buffer));
                    if(n == 0){
                        ls(Info, "read none");
                        break;
                    }
                    else if(n < 0){
                        ls(Fatal,"read error, code: %d, error string: %s", errno, strerror(errno));
                        break;
                    }
                    else{
                        // ls(Info, "read success");
                        buffer[n] = 0;
                        packageBuffer += buffer;

                        while(true){
                            string info = _callBack(packageBuffer);
                            if(info.empty()){
                                break;
                            }

                            write(fd, info.c_str(), info.size());
                        }
                    }
                }
                exit(0);
            }
            close(fd);
        }
    }


private:
    uint16_t _port;
    Socket listenSocket;
    func_t _callBack;
};